package com.indexingsystem.boss.filter;

import java.util.Set;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

/**
 * 角色判断校验.
 * 
 * @author Administrator
 *
 */
public class RoleFilter extends AccessControlFilter {

	private static String url = "http://118.31.66.123:8080";
//	private static String url = "http://192.168.0.155:8080";
//	private static String url = "http://118.31.66.123:8082";
	
	static final String LOGIN_URL = url+"/#/login";
	static final String UNAUTHORIZED_URL = url+"/digitalhome-boss/jsp/unauthorized.jsp";
	// static final String UNAUTHORIZED_URL =
	// "http://www.sojson.com/unauthorized.html";

	@SuppressWarnings({"unchecked"})
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		Subject subject = getSubject(request, response);
		String[] arra = (String[]) mappedValue;

		if (arra == null || arra.length == 0) {  
            //no roles specified, so nothing to check - allow access.  
            return true;  
        } 
		Set<String> roles = CollectionUtils.asSet(arra);  
		for (String role : roles) {
			if (subject.hasRole("role:" + role)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 校验授权.
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

		Subject subject = getSubject(request, response);
		if (subject.getPrincipal() == null) {// 表示没有登录，重定向到登录页面
			saveRequest(request);
			WebUtils.issueRedirect(request, response, LOGIN_URL);
		} else {
			if (StringUtils.hasText(UNAUTHORIZED_URL)) {// 如果有未授权页面跳转过去
				WebUtils.issueRedirect(request, response, UNAUTHORIZED_URL);
			} else {// 否则返回401未授权状态码
				WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
			}
		}
		return false;
	}
}